package is.ru.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * Created in IntelliJ IDEA.
 * Students: Jón Geir Sigurbjörnsson, Kristinn Helgi Hilmarsson, Jón Rúnar Arnarsson
 * Class: T-408-STNE, Stýrikerfi og netkerfi, 2011-1
 * Project: Programming assignment 3: HTTP web server
 * Date: 16.3.2011
 * Time: 20:17
 */

public class UDPRequestHandler  implements Runnable
{
    DatagramSocket socket;
    InetAddress address;
    int port;
    String request;

    // Constructor
    public UDPRequestHandler(DatagramSocket socket, String request, InetAddress address, int port)
    {
        this.socket = socket;
        this.address = address;
        this.port = port;
        this.request = request;

        // Make new Thread
        Thread t = new Thread(this);
        t.start();
    }

    public void run()
    {
        try
        {
            System.out.println(request.replaceAll("\\u0000+$", ""));
            // Make new request
            Request handleRequest = new Request(request);
            String message = handleRequest.getResponse();

            // Get bytes from message
            byte[] sendData = message.getBytes();
            DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length, address, port);

            socket.send(sendPacket);
        } catch (IOException e)
        {
            System.out.println("UDPRequestHandler IOException");
            e.printStackTrace();
        }
    }
}
